/* $Id: imgflip.jquery.js 14 2009-07-09 09:48:56Z geraldb $

Unobtrusive Accessible jQuery Tab Catching For Textareas

Overview:
	Insert tabs when tab is pushed on a textarea

Usage:
	$('textarea').catchtabs();

Parameters:

Authors:
	gburns

TODO:

*/

(function($) {
$.fn.catchtabs = function(parameters) {
	return this.each(function() {
		var $this = $(this)
		if ( !$this.is('textarea') ) $('textarea', this).catchtabs();
		$this.bind('keydown', $.catchtabs.catchTab);
	});
};

$.catchtabs = {
	// TAB support
	setSelectionRange: function(input, selectionStart, selectionEnd) {
		if (input.setSelectionRange) {
			input.focus();
			input.setSelectionRange(selectionStart, selectionEnd);
		} else if (input.createTextRange) {
			var range = input.createTextRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		}
	},

	replaceSelection: function (input, replaceString) {
		if ( input.setSelectionRange ) {
			var selectionStart = input.selectionStart;
			var selectionEnd = input.selectionEnd;
			input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
		
			if ( selectionStart != selectionEnd ) {
				$.catchtabs.setSelectionRange(input, selectionStart, selectionStart + 	replaceString.length);
			} else {
				$.catchtabs.setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
			}

		} else if ( document.selection ) {
			var range = document.selection.createRange();

			if ( range.parentElement() == input ) {
				var isCollapsed = range.text == '';
				range.text = replaceString;

				 if ( !isCollapsed )  {
					range.moveStart('character', -replaceString.length);
					range.select();
				}
			}
		}
	},

	// We are going to catch the TAB key so that we can use it, Hooray!
	catchTab: function(e){
		var item;
		if ( !e ) var e = window.event;
		if ( e.target ) item = e.target;
		else if ( e.srcElement ) item = e.srcElement;
		if ( item.nodeType == 3 ) // defeat Safari bug
			item = item.parentNode;

		if ( navigator.userAgent.match("Gecko") ) {
			c = e.which;
		} else {
			c = e.keyCode;
		}

		if ( c==9 ) {
			$.catchtabs.replaceSelection(item, String.fromCharCode(9));
			setTimeout(function(item) { return function() { item.focus() }  }(item),0);	
			return false;
		}
	}
}
})(jQuery);